package com.cbc.ourgame.slideshowmaker.components.audio
{
	import assets.volume.SmallVolumeControlAsset;
	import assets.volume.VolumeControlAsset;
	
	import com.cbc.ourgame.slideshowmaker.components.ui.PressButton;
	
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.media.SoundMixer;
	import flash.media.SoundTransform;
	
	public class VolumeController
	{
		private var _stage:Stage;
		private var _view:Sprite;
		
		private var _mute:PressButton;
		private var _full:PressButton;
		private var _indicator:Sprite;
		private var _track:Sprite;
		
		private var _volume:Number;
		
		public function get view():Sprite { return _view; }
		public function get volume():Number { return _volume; }
		
		public function set volume(value:Number):void
		{
			setVolume(value * _track.width);
		}
		
		public function VolumeController(large:VolumeControlAsset = null, small:SmallVolumeControlAsset = null)
		{	
			if(large == null) makeSmall(small)
			else makeLarge(large);
			
			_mute.addCallback(onMutePress);
			_full.addCallback(onFullPress);
			
			_track.buttonMode = true;
			_track.addEventListener(MouseEvent.MOUSE_DOWN, onIndicatorDown);
			
			volume = 0.5;
		}
		
		private function addStage(stage:Stage):void
		{
			_stage = stage;
		}
		
		private function makeLarge(item:VolumeControlAsset):void
		{
			_view = item;
			_mute = new PressButton(item.mute);
			_full = new PressButton(item.full);
			_indicator = item.indicator;
			_track = item.track;
		}
		
		private function makeSmall(item:SmallVolumeControlAsset):void
		{
			_view = item;
			_mute = new PressButton(item.mute);
			_full = new PressButton(item.full);
			_indicator = item.indicator;
			_track = item.track;
		}
		
		private function onMutePress(e:Event):void
		{
			setVolume(_indicator.width - 2);
		}
		
		private function onFullPress(e:Event):void
		{
			setVolume(_indicator.width + 2);
		}
		
		private function onIndicatorDown(e:MouseEvent):void
		{
			setVolume(_track.mouseX);
			_view.stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
			_view.stage.addEventListener(MouseEvent.MOUSE_UP, onIndicatorUp);
		}
		
		private function onIndicatorUp(e:MouseEvent):void
		{
			_view.stage.removeEventListener(MouseEvent.MOUSE_UP, onIndicatorUp);
			_view.stage.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
		}
		
		private function onMouseMove(e:MouseEvent):void
		{
			setVolume(_track.mouseX);
		}
		
		private function setVolume(value:Number):void
		{
			_indicator.width = Math.max(0, Math.min(value, _track.width));
			_volume = _indicator.width/_track.width;
			SoundMixer.soundTransform = new SoundTransform(_volume);
		}

	}
}